#!/bin/bash
# usage: curl -s https://gitee.com/liuhuan-devops/online/raw/master/init.sh | bash -

#程序终止程序
trap 'onCtrlC' INT
function onCtrlC () {
    echo '退出脚本'
exit
}

# 脚本初始化
dir_init=/tmp/xbazhen_init
[[ ! -d $dir_init ]] && mkdir $dir_init
time_Y=$(date +%Y)
time_m=$(date +%m)
time_d=$(date +%d)
time_H=$(date +%H)
time_M=$(date +%M)
time_S=$(date +%S)
time_full=$time_Y-$time_m$time_d-$time_H$time_M$time_S
 echo 当前时间: $time_full


# 获取发行版信息
function get_dist(){
    ls /etc | grep 'centos-release' >/dev/null 2>&1
    result=$(echo $?)
    if [[ $result == 0 ]]; then
        dist='CentOS'
    else
        dist='Unknow'
    fi
}
get_dist

# 获取CentOS版本信息
function get_centos_version(){
    centos_version=$(cat /etc/centos-release | grep -oP "\d{1,2}\.\d{1,2}")         # 获取详细版本，例如: 6.6   7.3
    centos_version_main=$(echo $centos_version | awk -F . '{print $1}')             # 获取主版本，例如: 6   7
    # echo $centos_version $centos_version_main
}

#如果为centos系统，就获取详细版本
case $dist in
CentOS)
    get_centos_version
    dist_version=$centos_version
    ;;
*)
esac

# 获取架构信息  暂时不区分 amd64 ia64之类的
function get_arch(){
    getconf LONG_BIT | grep '64' >/dev/null 2>&1
    result=$(echo $?)
    if [[ $result == 0 ]]; then
        arch='64'
    else
        arch='32'
    fi    
}
get_arch

# 设置主源(Base源 + epel源 + docker源 + mysql源)
function set_source_centos(){    
    if  [[ $centos_version_main == "7" ]]; then
        # Base-腾讯云源
        curl -s -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.cloud.tencent.com/repo/centos7_base.repo
        # epel
        yum install -y epel-release # 安装这个，是因为总有些软件要装，然后把地址就改成了epel官方的。
        # epel-腾讯云源
        curl -s -o /etc/yum.repos.d/epel.repo http://mirrors.cloud.tencent.com/repo/epel-7.repo
        # mysql-腾讯云源
        # 官方: https://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm
        # 下面这个安装，结果是mysql5.6的。
        # rpm -Uvh https://mirrors.ustc.edu.cn/mysql-repo/yum/mysql-5.7-community/el/7/x86_64/mysql-community-release-el7-7.noarch.rpm
        # curl -s -o /etc/yum.repos.d/mysql-community.repo $url_resource/repos/mysql/mysql-community_ustc_tmp1.repo

    elif [[ $centos_version_main == "8" ]]; then
        #阿里云镜像源
	mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-vault-8.5.2111.repo
        # epel
        yum install -y epel-release
        curl -s -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-6.repo
    else 
        echo "暂不支持CentOS6及以下的版本, 请手动退出脚本..."
        sleep 1000000000
    fi
    yum clean all
    yum makecache fast
}

function set_source(){
    if [[ $dist == "CentOS" ]]; then
        set_source_centos
    fi
}

# 安装软件
function install_basic_software(){
    yum install -y \
        net-tools \
        sysstat lsof \
        gcc gcc-c++ \
        expect \
        ntp ntpdate crontabs \
        wget lrzsz tree vim telnet wget openssh-clients unzip zip pigz \
        tomcat-native apr \
        nc net-snmp-utils \
        subversion git \
        bind-utils psmisc \
        man \
        nfs-utils yum-utils
	chrony
}

# 设置selinux, 完成后需要重启服务器
function set_selinux(){
    getenforce | grep -i 'enforcing' && setenforce 0
    sed -i '/^SELINUX=/ c\SELINUX=disabled' /etc/selinux/config
    sed -i '/^SELINUX=/ c\SELINUX=disabled' /etc/sysconfig/selinux
}

function set_firewall(){
    if [[ $dist == "CentOS" ]]; then
        # 备份防火墙规则表
        iptables -vnL > $dir_init/firewall@bak$time_full
        if [[ $centos_version_main == "7"|| $centos_version_main == "8" ]]; then
            systemctl stop firewalld
            systemctl disable firewalld
        elif [[ $centos_version_main == "6" ]]; then
            service iptables stop
            chkconfig iptables off
        fi        
    fi
}

function get_lanIp(){
    # CentOS7
    # 检测网卡的那里，egrep -A1 'ens[0-9]{1,3}: |eth[0-9]{1,3}: |em[0-9]{1,3}: |bond[0-9]{1,3}: '，可以示单引号，也可以是双引号。centos6 7都支持两种引号
    # enp2s0 是极夜迷你主机的有线网卡设备名
    # 兼容centos6  eth[0-9]{1,3}:{0,1}
    if [[ $centos_version_main == "7" ]]; then
        lanIpALL=$(/sbin/ifconfig | egrep -A1 'enp2s[0-9]{1,3}: |ens[0-9]{1,3}: |eth[0-9]{1,3}: |eno[0-9]{1,3}: |em[0-9]{1,3}: |bond[0-9]{1,3}: ' | sed '/^--/ d' | awk '/inet / {print $2}'| egrep '^10\.|^172\.1[6-9]\.|^172\.2[0-9]\.|^172.3[0-1]\.|^192\.168')
    # CentOS6
    elif [[ $centos_version_main == "6" ]]; then
        lanIpALL=$(/sbin/ifconfig | sed -e '/bond[0-9]:/,/^$/ d' -e '/eth[0-9]:/,/^$/ d' -e '/em[0-9]:/,/^$/ d' | awk '/inet addr:/ {print $2}' | awk -F: '{print $2}' | egrep '^10\.|^172\.1[6-9]\.|^172\.2[0-9]\.|^172.3[0-1]\.|^192\.168')
    fi      

    num_lanIpALL=$(echo $lanIpALL | wc -w)
    if [ "$num_lanIpALL" -eq 1 ] ; then
        lanIp=$lanIpALL
    elif [ "$num_lanIpALL" -eq 0 ] ; then
        echo "未找到内网IP，请检查脚本是否不正确..."
        sleep 1000000000
    else
        echo "Warning! The number of lanIp is not 1(>=2), please choose one and input(IP_LAN1):" # 大于1
        sleep 1000000000
        echo $lanIpALL
        read lanIp
    fi
    # 把获取到的第一个IP写入进去
    echo "export IP_LAN1=$lanIp" > /etc/profile.d/ip_lan1.sh
}

# 设置时区为 +8
function set_timezone(){
    cp -f /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
    # ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
}

# ntpd
function set_ntpd(){
    if [[ $dist == "CentOS" ]]; then
        if [[ $centos_version_main == "7" ]]; then
            systemctl start ntpd
            systemctl enable ntpd
        elif [[ $centos_version_main == "8" ]]; then
		systemctl start chronyd
		systemctl enable chronyd
		sed 's/pool 2.centos.pool.ntp.org iburst/server ntp.aliyun.com iburst\nserver cn.ntp.org.cn iburst/g' /etc/chrony.conf
        fi
    fi    
}

# crond
function set_crond(){
    if [[ $dist == "CentOS" ]]; then
        if [[ $centos_version_main == "7"|| $centos_version_main == "8" ]]; then
            systemctl start crond
            systemctl enable crond
        elif [[ $centos_version_main == "6" ]]; then
            service crond start
            chkconfig crond on
        fi            
    fi    
}

# auto_start
function set_auto_start(){
    if [[ $dist == "CentOS" ]]; then
        if [[ $centos_version_main == "7"|| $centos_version_main == "8" ]]
        then
            chmod +x /etc/rc.local
        fi            
    fi    
}

function set_sshd(){
    # sshd_config
    # 0. 关闭ssh的gssapi认证
    # 1. 关闭远程连接时 DNS 的IP反向解析请求
    # 2. 远程会话时,保持连接
    cfg_file_sshd='/etc/ssh/sshd_config'
    cfg_cmd_nodns='UseDNS no'
    # 主替换命令
    sed -i 's/^GSSAPIAuthentication yes/#GSSAPIAuthentication yes/g' $cfg_file_sshd
    sed -i 's/^GSSAPIDelegateCredentials no/#GSSAPIDelegateCredentials no/g' $cfg_file_sshd
    sed -i '/UseDNS/ c\UseDNS no' $cfg_file_sshd
    # 备用替换命令
    # 配置文件,只检索 'UseDNS' 而不是'UseDNS no' , 因为UseDNS 和no可以不止一个空格
    grep "UseDNS" $cfg_file_sshd >/dev/null || echo "$cfg_cmd_nodns" >> $cfg_sshd
    # ssh客户端保持连接
    sed -i "/^#ClientAliveInterval 0/ c\ClientAliveInterval 60" $cfg_file_sshd
    sed -i "/^#ClientAliveCountMax 3/ c\ClientAliveCountMax 3" $cfg_file_sshd
    
    # 6 7 都通用的
    service sshd reload
    # if [[ $centos_version_main == "7" ]]; then
    #     systemctl reload sshd
    # elif [[ $centos_version_main == "6" ]]; then
    #     service sshd reload
    # fi  
}

function set_dir(){
    # 新建目录
    [ ! -d /data ] && mkdir /data
    
}

function set_docker(){
# 仅在centos7上安装docker
if [[ $centos_version_main == "7"|| $centos_version_main == "8" ]]; then
# 安装docker-compose
yum remove -y docker-compose    # 不移除，下面不会重新安装。

# docker源
# https://mirrors.ustc.edu.cn/docker-ce/linux/centos/docker-ce.repo
# curl -s -o /etc/yum.repos.d/docker-ce.repo $url_resource/repos/docker/7/docker_ustc.repo
# 更换为科大的
# sed -i "s#download.docker.com#mirrors.ustc.edu.cn/docker-ce#g" /etc/yum.repos.d/docker-ce.repo

# 阿里云源
# yum install -y yum-utils device-mapper-persistent-data lvm2
# yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

# 腾讯云源
docker_service='/etc/systemd/system/multi-user.target.wants/docker.service'
[ -f $docker_service ] && mv -f $docker_service /tmp/docker.service.bak
yum install -y yum-utils device-mapper-persistent-data lvm2
curl -s -o /etc/yum.repos.d/docker-ce.repo https://download.docker.com/linux/centos/docker-ce.repo
sudo sed -i 's+download.docker.com+mirrors.cloud.tencent.com/docker-ce+' /etc/yum.repos.d/docker-ce.repo

yum makecache fast

# 安装docker
# https://mirrors.cloud.tencent.com/docker-ce/linux/centos/7/x86_64/stable/Packages/docker-ce-18.09.9-3.el7.x86_64.rpm
# https://mirrors.cloud.tencent.com/docker-ce/linux/centos/7/x86_64/stable/Packages/docker-ce-19.03.13-3.el7.x86_64.rpm
yum install -y docker-ce-19.03.13-3.el7.x86_64     # 19.03
# yum install -y docker-ce                             # 后面出现了20.10，和k8s暂时不兼容。

# 可能由于/etc/systemd/system/multi-user.target.wants/docker.service和/usr/lib/systemd/system/docker.service不一致。
# Created symlink from /etc/systemd/system/multi-user.target.wants/docker.service to /usr/lib/systemd/system/docker.service.

# {
#   "registry-mirrors": ["https://docker.mirrors.ustc.edu.cn"]
# }
# "registry-mirrors": ["https://zahdqyo7.mirror.aliyuncs.com"],     # 最快的

# {
#    "insecure-registries":["http://172.17.9.81:5000"]
# }

[ ! -d "/etc/docker" ] && mkdir -p /etc/docker

echo '{
  "registry-mirrors": ["https://zahdqyo7.mirror.aliyuncs.com"],
  "data-root": "/data/docker",
  "log-driver":"json-file",
  "log-opts": {"max-size":"20m", "max-file":"1"},
  "exec-opts": ["native.cgroupdriver=systemd"]
}' > /etc/docker/daemon.json

echo "\
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
" > /etc/sysctl.d/docker1.conf
sysctl -p /etc/sysctl.d/docker1.conf    

# 设置开机自启动
systemctl enable docker
systemctl daemon-reload
systemctl restart docker
fi
}

# 检查是否已经执行过初始化脚本
function check_init_status(){
    if [[ $INIT_STATUS -ne 1 ]]; then
        echo "该系统已经执行过初始化脚本, 请使用 Ctrl+C 退出脚本..."
        sleep 1000000000
    else
        echo "该系统尚未执行过初始化脚本，请等待进一步检测..."
    fi
}

# 设置初始化状态，执行完毕之后，状态为1
function set_init_status(){
    echo "export INIT_STATUS=1" > /etc/profile.d/init_statu.sh
}

# 主函数
function main(){
    # 系统信息展示
    echo "本机系统为: ${dist}${dist_version} , 系统架构为: ${arch}位!"
    sleep 1

    # 检查此脚本是否兼容被初始化的系统
    support_dist="CentOS"
    echo $support_dist | grep $dist
    if [[ $? -ne 0 ]]; then
        echo "该初始化脚本暂不支持此发行版, 请使用 Ctrl+C 退出脚本..."
        sleep 1000000000
    else
        echo "系统兼容性检测通过, 开始执行初始化脚本..."
    fi
    
    # echo "\
    # +---------------------------------------+
    # |   your system is CentOS 6 x86_64      |
    # |        start optimizing.......        |
    # +---------------------------------------+
    # "

    set_source
    install_basic_software
    set_selinux
    set_firewall
    set_timezone
    set_ntpd
    set_crond
    set_auto_start
    set_dir
    docker info || set_docker       # 不重复安装docker
    set_init_status

    echo "\
    +-------------------------------------------------+
    |               optimizer is done                 |
    |   it's recommond to restart this server !       |
    +-------------------------------------------------+
    "
}
main

# 需要重启才能生效的有以下几个
